package com.example.backend.controller;

import com.example.backend.entity.StorageIn;
import com.example.backend.service.StorageInService;
import com.example.backend.util.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/storage-in")
public class StorageInController {
    @Autowired
    private StorageInService storageInService;

    @PostMapping
    public ApiResponse<String> addStorageIn(@RequestBody StorageIn storageIn) {
        storageInService.addStorageIn(storageIn);
        return ApiResponse.success("入库成功");
    }

    @GetMapping("/{id}")
    public ApiResponse<StorageIn> getStorageInById(@PathVariable Long id) {
        StorageIn storageIn = storageInService.getStorageInById(id);
        if (storageIn != null) {
            return ApiResponse.success(storageIn);
        }
        return ApiResponse.error(404, "入库记录不存在");
    }

    @GetMapping
    public ApiResponse<List<StorageIn>> getAllStorageIn() {
        return ApiResponse.success(storageInService.getAllStorageIn());
    }

    @PutMapping
    public ApiResponse<String> updateStorageIn(@RequestBody StorageIn storageIn) {
        storageInService.updateStorageIn(storageIn);
        return ApiResponse.success("更新成功");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteStorageIn(@PathVariable("id") Long id) {
        storageInService.deleteStorageIn(id);
        return ApiResponse.success("删除成功");
    }

//    @GetMapping("/order/{orderNumber}")
//    public ApiResponse<List<StorageIn>> getByOrderNumber(@PathVariable("orderNumber") String orderNumber) {
//        return ApiResponse.success(storageInService.getByOrderNumber(orderNumber));
//    }

    @GetMapping("/port/{portId}")
    public ApiResponse<List<StorageIn>> getStorageInByPortId(@PathVariable("portId") Long portId) {
        List<StorageIn> storageIns = storageInService.getStorageInByPortId(portId);
        return ApiResponse.success(storageIns);
    }

    @PostMapping("/batch")
    public ApiResponse<Integer> batchAddStorageIn(@RequestBody List<StorageIn> storageInList) {
        System.out.println("批量入库数据条数: " + storageInList.size());
        for (StorageIn s : storageInList) {
            if (s.getLicensePlate() == null || s.getInDate() == null) {
                System.out.println("数据有空字段: " + s);
                throw new RuntimeException("必填字段为空");
            }
        }
        int successCount = storageInService.batchAddStorageIn(storageInList);
        return ApiResponse.success(successCount);
    }

    @PostMapping("/clear")
    public ApiResponse<Integer> clearAll() {
        int count = storageInService.deleteAll();
        return ApiResponse.success(count);
    }
} 